import 'package:enterprise_v6_app/app/core/core.dart';

/// 表格
/// [xLen]: 横向有多少项
/// [yLen]: 纵向有多少项，不包括表头
/// [cellBuilder]: 单个格子的构造器
/// [headBuilder]: 表头的构造器
/// [padding]: 表格内边距
/// [cellPadding]: 单个格子的内边距
/// [alignment]: 内容对齐方式
class CustomTable extends StatelessWidget {
  const CustomTable({
    required this.xLen,
    required this.yLen,
    required this.cellBuilder,
    required this.headBuilder,
    super.key,
    this.padding,
    this.cellPadding,
    this.alignment,
    this.color,
  });

  final int xLen;
  final int yLen;
  final Widget Function(int x, int y) cellBuilder;
  final Widget Function(int x) headBuilder;
  final EdgeInsetsGeometry? padding;
  final EdgeInsetsGeometry? cellPadding;
  final Alignment? alignment;
  final Color? color;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10.w),
      ),
      padding: padding,
      child: Table(
        children: List.generate(
          yLen + 1,
          (y) => TableRow(
            decoration: y == 0
                ? BoxDecoration(
                    color: color ?? const Color(0xFFF1F2F7),
                    borderRadius: BorderRadius.circular(4.w),
                  )
                : y % 2 == 0
                    ? BoxDecoration(
                        color: color?.withAlpha(17) ?? const Color(0xFFF8F8FA),
                      )
                    : null,
            children: y == 0
                ? List.generate(xLen, (x) => _buildCell(x, y - 1, true))
                : List.generate(
                    xLen,
                    (x) => _buildCell(x, y - 1, false),
                  ),
          ),
        ),
      ),
    );
  }

  Widget _buildCell(int x, int y, bool isHead) {
    var child = isHead ? headBuilder(x) : cellBuilder(x, y);
    if (cellPadding != null) {
      child = Padding(
        padding: cellPadding!,
        child: child,
      );
    }
    if (alignment != null) {
      child = Align(
        alignment: alignment!,
        child: child,
      );
    }
    return child;
  }
}
